package sprites;

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;

import sprites.characteristic.PlayerSpawn;
import sprites.characteristic.PowerUp;
import main.ImageLoader;

public class Pacman extends Sprite {

	private final int MOVEMENT_DISTANCE = 3;

	private ArrayList<PlayerSpawn> playerSpawn;
	private HashMap<Point, Sprite> map;

	private KeyboardFocusManager kfm = KeyboardFocusManager
			.getCurrentKeyboardFocusManager();

	private final int MAX_HP = 3;
	private int hp = MAX_HP;

	private String name;

	public Pacman(String name) {
		setImage(ImageLoader.getImage("pacman.png"));
		active = false;
		kfm.addKeyEventDispatcher(new KeyEventDispatcher() {

			@Override
			public boolean dispatchKeyEvent(KeyEvent e) {
				if (e.getID() == 402) {
					switch (e.getKeyChar()) {
					case 'e':
						moveUp();
						break;
					case 's':
						moveLeft();
						break;
					case 'd':
						moveDown();
						break;
					case 'f':
						moveRight();
						break;
					default:
						break;
					}
				}
				return false;
			}
		});
	}

	private void moveUp() {
		int tmpY = getY() - MOVEMENT_DISTANCE;
		if (!getCollision(getX(), tmpY)) {
			setY(tmpY);
		}
	}

	private void moveLeft() {
		int tmpX = getX() - MOVEMENT_DISTANCE;
		if (!getCollision(tmpX, getY())) {
			setX(tmpX);
		}
	}

	private void moveRight() {
		int tmpX = getX() + MOVEMENT_DISTANCE;
		if (!getCollision(tmpX, getY())) {
			setX(tmpX);
		}
	}

	private void moveDown() {
		int tmpY = getY() + MOVEMENT_DISTANCE;
		if (!getCollision(getX(), tmpY)) {
			setY(tmpY);
		}
	}

	private boolean getCollision(int x, int y) {
		x = Math.round(x/DEF_TILE);
		y = Math.round(y/DEF_TILE);
		Sprite sp = map.get(new Point(x, y));
		if (sp == null)
			return false;

		if (sp.isPassable()) {
			if (sp instanceof PowerUp) {
				((PowerUp) sp).consume();
			}
			return false;
		}
		return true;
	}

	private void decreaseHp() {
		hp--;

		if (hp <= 0)
			gameOver();

		spawnPac();
	}

	private void gameOver() {
		// TODO: GAMEOVER!
		active = false;
	}

	@Override
	public void setActive(boolean b) {
		// SPAWN!
		if (b) {
			if (playerSpawn == null || playerSpawn.isEmpty()) {
				System.err.println("Spawns not set!");
				System.exit(1);
			}
			spawnPac();
		} else {
			gameOver();
		}
	}

	public void setSpawns(ArrayList<PlayerSpawn> playerSpawn) {
		this.playerSpawn = playerSpawn;
	}

	public void setMap(HashMap<Point, Sprite> map) {
		this.map = map;
	}

	public void spawnPac() {
		Random rand = new Random();
		int tmp = rand.nextInt(playerSpawn.size());
		PlayerSpawn ps = playerSpawn.get(tmp);

		setX(ps.getX());
		setY(ps.getY());
		System.out.println(x);
		System.out.println(y);
		active = true;
	}
}
